package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private static final String KEY_PREFIX="lock:";
    /**
     * 线程标识
     */
    private static final String THREAD_ID_PREFIX = UUID.randomUUID(true) + "-";

    private String name;

    private StringRedisTemplate stringRedisTemplate;

    private static DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        String threadId = THREAD_ID_PREFIX + Thread.currentThread().getId();
        Boolean isLock = stringRedisTemplate
                .opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId + "", timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(isLock);
    }

    @Override
    public void unlock() {
        //调用lua脚本
        List<String> list = Collections.singletonList(KEY_PREFIX + name);
        stringRedisTemplate
                .execute(UNLOCK_SCRIPT, list, THREAD_ID_PREFIX + Thread.currentThread().getId());
      /*  //获取线程标识
       String threadId =  THREAD_ID_PREFIX + Thread.currentThread().getId();
       //获取锁中的标识
        String lockId = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (threadId.equals(lockId)){
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }*/
    }
}
